package com.xiaoxiang.cameracontrol;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;


public class MainActivity2 extends AppCompatActivity implements View.OnClickListener, Handler.Callback {
    private String[] permissions = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private Handler handler;
    private AutoFitTextureView mTextureview;
    private Button mTakePictureBtn;//拍照
    private Button mVideoRecodeBtn;//开始录像
    private LinearLayout mVerticalLinear;
    private Button mTakePictureBtn2;//拍照 横,竖屏状态分别设置了一个拍照,录像的按钮
    private Button mVideoRecodeBtn2;//开始录像
    private LinearLayout mHorizontalLinear;
    private Button mVHScreenBtn;
    private CameraController mCameraController;
    private boolean mIsRecordingVideo; //开始停止录像
    //public static String BASE_PATH = Environment.getExternalStorageDirectory() + "/";
    public static String BASE_PATH = "/sdcard/";

    private Button exit_btn;
    private TextView person_id;
    private TextView now_seqquence;
    private TextView server;
    private TextView local;
    private TextView device;
    private TextView storage;
    private TextView camera_state;


    private int now_battery = 0;
    private TextView battery_info;
    private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_BATTERY_CHANGED.equals(action)){
                now_battery = intent.getIntExtra("level", 0);
                battery_info.setText("电量剩余: "+String.valueOf(now_battery)+"%");
                storage.setText("存储: "+String.valueOf(getStorage())+"GB");
                send_states_to_server();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getSupportActionBar() != null){
            getSupportActionBar().hide();
        }
        setContentView(R.layout.activity_main2);
        SysApplication.getInstance().addActivity(this);
        // requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
        setContentView(R.layout.activity_main2);
        this.battery_info = findViewById(R.id.electric);
        this.person_id = findViewById(R.id.person_id);
        this.now_seqquence = findViewById(R.id.now_sequeence);
        this.server = findViewById(R.id.server);
        this.local = findViewById(R.id.local);
        this.device = findViewById(R.id.device);
        this.storage = findViewById(R.id.storage);
        this.camera_state = findViewById(R.id.camera_state);
        this.server.setText("服务器: "+LoginActivity.socket_client.server_host);
        this.local.setText("本机地址: "+LoginActivity.socket_client.local_host);
        this.device.setText("本机序号: "+LoginActivity.socket_client.my_id);
        this.storage.setText("存储: "+String.valueOf(this.getStorage())+"GB");

        //这里的this不是上下文，是Activity对象！
        PermissionsUtils.getInstance().chekPermissions(this, permissions, permissionsResult);
        registerReceiver(mBatInfoReceiver,
                new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        this.handler = new Handler(this);
        LoginActivity.socket_client.setCameraHandler(this.handler);
        Log.i("A", "已经Create");
    }

    private PermissionsUtils.IPermissionsResult permissionsResult = new PermissionsUtils.IPermissionsResult() {
        @Override
        public void passPermissons() {
            //授权后的操作
            //获取相机管理类的实例
            mCameraController = CameraController.getmInstance(MainActivity2.this);
            initView();
            //判断当前横竖屏状态
            if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                mVHScreenBtn.setText("切换为竖屏");
            } else {
                mVHScreenBtn.setText("切换为横屏");

            }
        }

        @Override
        public void forbitPermissons() {
            //未授权，请手动授权

        }


    };


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[]
            permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //就多一个参数this
        PermissionsUtils.getInstance().onRequestPermissionsResult(this, requestCode,
                permissions, grantResults);

    }

    private void initView() {
        mTextureview = (AutoFitTextureView) findViewById(R.id.textureview);
        mTakePictureBtn = (Button) findViewById(R.id.take_picture_btn);
        mTakePictureBtn.setOnClickListener(this);
        mVideoRecodeBtn = (Button) findViewById(R.id.video_recode_btn);
        mVideoRecodeBtn.setOnClickListener(this);
        mVerticalLinear = (LinearLayout) findViewById(R.id.vertical_linear);
        mTakePictureBtn2 = (Button) findViewById(R.id.take_picture_btn2);
        mTakePictureBtn2.setOnClickListener(this);
        mVideoRecodeBtn2 = (Button) findViewById(R.id.video_recode_btn2);
        mVideoRecodeBtn2.setOnClickListener(this);
        mHorizontalLinear = (LinearLayout) findViewById(R.id.horizontal_linear);
        mVHScreenBtn = (Button) findViewById(R.id.v_h_screen_btn);
        mVHScreenBtn.setOnClickListener(this);

        exit_btn = findViewById(R.id.exit_btn);
        exit_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(LoginActivity.socket_client!=null){
                    LoginActivity.socket_client.close();
                }
                SysApplication.getInstance().exit();
            }
        });

        //判断当前屏幕方向
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            //竖屏时
            mHorizontalLinear.setVisibility(View.GONE);
            mVerticalLinear.setVisibility(View.GONE);
        } else {
            //横屏时
            mVerticalLinear.setVisibility(View.GONE);
            mHorizontalLinear.setVisibility(View.GONE);
        }
        mCameraController.InitCamera(mTextureview);
        mCameraController.setFolderPath(BASE_PATH);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.take_picture_btn:
                mCameraController.takePicture();
                break;
            case R.id.video_recode_btn:
                if (mIsRecordingVideo) {
                    mIsRecordingVideo = !mIsRecordingVideo;
                    mCameraController.stopRecordingVideo();
                    mVideoRecodeBtn.setText("开始录像");
                    mVideoRecodeBtn2.setText("开始录像");
                    Toast.makeText(this, "录像结束", Toast.LENGTH_SHORT).show();
                } else {
                    mVideoRecodeBtn.setText("停止录像");
                    mVideoRecodeBtn2.setText("停止录像");
                    mIsRecordingVideo = !mIsRecordingVideo;
                    mCameraController.startRecordingVideo();
                    Toast.makeText(this, "录像开始", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.take_picture_btn2:
                mCameraController.takePicture();
                break;
            case R.id.video_recode_btn2:
                if (mIsRecordingVideo) {
                    mIsRecordingVideo = !mIsRecordingVideo;
                    mCameraController.stopRecordingVideo();
                    mVideoRecodeBtn.setText("开始录像");
                    mVideoRecodeBtn2.setText("开始录像");
                    Toast.makeText(this, "录像结束", Toast.LENGTH_SHORT).show();
                } else {
                    mVideoRecodeBtn.setText("停止录像");
                    mVideoRecodeBtn2.setText("停止录像");
                    mIsRecordingVideo = !mIsRecordingVideo;
                    mCameraController.startRecordingVideo();
                    Toast.makeText(this, "录像开始", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.v_h_screen_btn:
                //判断当前屏幕方向
                if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                    //切换竖屏
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    Toast.makeText(MainActivity2.this, "竖屏了", Toast.LENGTH_SHORT).show();
                } else {
                    //切换横屏
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    Toast.makeText(MainActivity2.this, "横屏了", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public boolean handleMessage(@NonNull Message message) {
        switch(message.what){
            case CameraSocket.START_RECORD:
                if(this.mIsRecordingVideo){
                    this.mCameraController.stopRecordingVideo();
                }
                this.mCameraController.startRecordingVideo();
                this.mIsRecordingVideo = true;
                this.camera_state.setText("正在录制");
                this.camera_state.setTextColor(Color.parseColor("#FF0000"));
                this.send_states_to_server();
                break;
            case CameraSocket.STOP_RECORD:
                Log.i("Camera", "收到停止录像的信息");
                if(mIsRecordingVideo){
                    Log.i("Camera", "停止controller录像...");
                    this.mCameraController.stopRecordingVideo();
                }
                Log.i("Camera", "controller录像已停止，准备发送状态信息...");
                this.mIsRecordingVideo = false;
                this.camera_state.setText("已停止");
                this.camera_state.setTextColor(Color.parseColor("#EEEEEE"));
                this.send_states_to_server();
                break;
            case CameraSocket.NEW_SEQUEENCE:
                String data = (String) message.obj;
                String[] param = data.split("&");
                if(param==null || param.length<2){
                    break;
                }
                String save_folder = createFolder(param);
                mCameraController.setFolderPath(save_folder);
                this.now_seqquence.setText("当前序列: " + param[1]);
                this.person_id.setText("行人ID: " + param[0]);
                break;
        }


        return false;
    }

    private String createFolder(String[] param){
        String traget_folder = "/sdcard" +
                "/data_collection/"+param[0]+"/"+param[1]+"/"+LoginActivity.socket_client.my_id+"/";
        new File(traget_folder).mkdirs();
        return traget_folder;
    }


    private int getStorage(){
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long availableBytes = 0;
        availableBytes = stat.getAvailableBytes();
        return (int)(availableBytes/(1024*1024*1024));

    }

    private void send_states_to_server(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                int state = 0;
                if(mIsRecordingVideo){
                    state=1;
                }
                LoginActivity.socket_client.send_state(state, now_battery, getStorage());
            }
        }).start();
    }


    @Override
    public void onPause(){


        super.onPause();
    }

    @Override
    public void onResume(){
        super.onResume();
    }
}
